package com.cet.algorithm.字符串;

import java.util.Arrays;

/**
 * @program: algorithm
 * @description: KMP算法
 * @author: 陈恩涛
 * @create: 2022-03-22 11:03
 **/
public class KMP {

    private String patten;

    public KMP(String patten) {
        this.patten = patten;
    }

    public String getPatten() {
        return patten;
    }

    public void setPatten(String patten) {
        this.patten = patten;
    }

    /**
     * 构建前缀表
     * 某个字符失配时，前缀表会告诉你下一步匹配中，模式串应该跳到哪个位置
     * @param next
     * @param s
     */
    private void getNext(int[] next, String s) {
        // j指向前缀的末尾
        int j = 0;
        next[0] = 0;
        // i 指向后缀的末尾
        for (int i = 1; i < s.length(); i++) {
            while (j > 0 && s.charAt(j) != s.charAt(i)) {
                // 这里看实现方式，在这里看前一位对应的next数组值
                j = next[j - 1];
            }
            if (s.charAt(j) == s.charAt(i)) {
                j++;
            }
            next[i] = j;
        }
    }

    /**
     * 子字符串查询
     * @param haystack 文本串
     * @param needle 模式串
     * @return
     */
    public int strStr(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        int[] next = new int[needle.length()];
        getNext(next, needle);
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == needle.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        KMP kmp = new KMP("aabaaf");
        int[] next = new int[kmp.getPatten().length()];
        kmp.getNext(next, kmp.getPatten());
        Arrays.stream(next).forEach(System.out::println);
        System.out.println(kmp.strStr("hello", "ll"));
    }
}
